﻿using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace MS_UI
{
    public delegate void ShowMsgDelegate(byte[] msg);
    public class LgtCOM
    {
        //创建一个串口对象
        private SerialPort MyCom = new SerialPort();

        //【2】创建委托变量
        public ShowMsgDelegate ShowMsg;



        #region 连接和断开连接

        public bool Connect(int iBaudRate, string iPortName, int iDataBits, Parity iParity, StopBits iStopBits)
        {
            //如果打开，先关闭

            if (MyCom.IsOpen)
            {
                MyCom.Close();
            }

            //设置串口属性

            MyCom.PortName = iPortName;
            MyCom.BaudRate = iBaudRate;
            MyCom.StopBits = iStopBits;
            MyCom.Parity = iParity;
            MyCom.DataBits = iDataBits;

            //设置串口事件
            MyCom.ReceivedBytesThreshold = 1;
            MyCom.DataReceived += MyCom_DataReceived;

            //打开串口
            try
            {
                MyCom.Open();
            }
            catch (Exception)
            {
                //写入日志
                return false;
            }

            return true;
        }

        public void DisConnect()
        {
            //如果打开，先关闭

            if (MyCom.IsOpen)
            {
                MyCom.Close();
            }
        }

        #endregion

        #region 数据接收
        private void MyCom_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            //先获取缓冲区的长度
            int ByteToRead = MyCom.BytesToRead;

            //因为一帧报文是9个字节
            if (ByteToRead >= 9)
            {
                //定义一个字节数组
                byte[] rcv = new byte[ByteToRead];

                //读取缓冲区里的数据放到字节数组中
                MyCom.Read(rcv, 0, ByteToRead);

                //这里如果想把字节数组给到主线程，需要使用委托

                ShowMsg?.Invoke(rcv);
            }

        }
        #endregion

        #region 命令发送

        #endregion


        /// <summary>
        /// Z轴校零
        /// </summary>
        /// <returns></returns>
      
        public bool GetDistance()
        {
            byte[] send;

            send = new byte[7] { 0x80, 0x01, 0x03, 0x00, 0x04, 0x00, 0x16 };
            try
            {

                if (MyCom.BytesToRead == 0)
                {
                    MyCom.Write(send, 0, send.Length);
                }

            }
            catch (Exception)
            {
                return false;
            }
            return true;

        }
        
    }

}
